import { defineStore } from 'pinia';
import { login, register, logout, refreshToken, getCurrentUser } from '@/api/user';
import { useMenuStore } from '@/store/menu';
import { getMenuTreeNoButton, getRoleMenus, getUserMenus } from '@/api/menu'
import { addDynamicRoutes } from '@/router/dynamicRoutes';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    refreshToken: localStorage.getItem('refreshToken') || '',
    user: JSON.parse(localStorage.getItem('user') || 'null'),
  }),
  actions: {
    async loginAction(data) {
      try {
        const res = await login(data);
        this.token = res.data.data.accessToken;
        this.refreshToken = res.data.data.refreshToken;
        localStorage.setItem('token', this.token);
        localStorage.setItem('refreshToken', this.refreshToken);
        this.user = res.data.data.userInfo;
        localStorage.setItem('user', JSON.stringify(this.user));
        // 登录成功后拉取当前用户权限菜单
        const menuStore = useMenuStore();
        const roleId = this.user.roleIdList[0];
        const resMenu = await getRoleMenus(roleId);
        menuStore.setMenuTree(resMenu.data.data || []);
        console.log("新增菜单",resMenu.data.data)
        addDynamicRoutes(resMenu.data.data || []);
        return res;
      } catch (error) {
        throw error;
      }
    },
    async registerAction(data) {
      await register(data);
    },
    async logoutAction() {
      try {
        const res = await logout(this.token);
        // 清理本地token和用户信息
        this.token = '';
        this.refreshToken = '';
        this.user = null;
        localStorage.removeItem('token');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('user');
        const menuStore = useMenuStore();
        menuStore.clearMenu();
        return res; // 返回后端响应，便于外部判断res.data.code
      } catch (error) {
        // 也要清理本地token和用户信息
        this.token = '';
        this.refreshToken = '';
        this.user = null;
        localStorage.removeItem('token');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('user');
        const menuStore = useMenuStore();
        menuStore.clearMenu();
        throw error;
      }
    },
    async refreshTokenAction() {
      const res = await refreshToken(this.refreshToken);
      this.token = res.data.data.accessToken;
      this.refreshToken = res.data.data.refreshToken;
      localStorage.setItem('token', this.token);
      localStorage.setItem('refreshToken', this.refreshToken);
    },
    async fetchUser() {
      try {
        const res = await getCurrentUser();
        this.user = res.data.data;
        localStorage.setItem('user', JSON.stringify(this.user));
      } catch (error) {
        throw error;
      }
    },
  },
});
